<template>
  <el-row style="position: relative">
    <el-col
      v-for="input in inputs"
      :key="input.$index"
      :span="getInputStyle(input).span || 24"
      :style="getInputStyle(input).style || {}"
      class="li"
    >
      <el-form-item
        :label="input.label"
        :prop="input.field"
        :rules="input.traits.includes('disabled') ? [] : input.rules"
      >
        <slot :name="input.type" :input="input" :form="form">
          <!-- 后备内容 -->
          <el-input
            v-model="form[input.field]"
            :placeholder="input.placeholder"
            :disabled="input.traits.includes('disabled')"
          />
        </slot>
        <template v-if="['image', 'file', 'images', 'files'].includes(input.type)" v-slot:label>
          <div>{{ input.label }}</div>
          <div style="color: #909399">{{ input.placeholder }}</div>
        </template>
      </el-form-item>
      <el-popover
        v-if="popover = operationMap[input.field].popover"
        placement="bottom-end"
        class="popover"
        :title="popover.title || '说明'"
        :width="popover.width"
        :trigger="popover.trigger || 'click'"
      >
        <div class="popover-content">
          <pre class="popover-pre">{{ popover.content }}</pre>
        </div>
        <i slot="reference" class="el-icon-question" />
      </el-popover>
    </el-col>
  </el-row>
</template>

<script>
export default {
  name: 'FormItem',
  filters: {
    popover(input) {
      return input.operations.find(operation => {
        if (operation.action === 'popover') {
          return operation
        }
      })
    }
  },
  // eslint-disable-next-line vue/require-prop-types
  props: ['inputs', 'operation', 'form'],
  data() {
    return {
      // 存储每个字段的操作
      operationMap: {}
    }
  },
  created() {
    // operationMap 的结构: operationMap[input.field][operation.action] = operation
    this.inputs.forEach(input => {
      if (!this.operationMap[input.field]) {
        this.operationMap[input.field] = {}
      }
      input.operations.forEach(operation => {
        this.operationMap[input.field][operation.action] = operation
      })
    })
  },
  methods: {
    // 输入框的样式
    getInputStyle(input) {
      return input.operations.find(operation => {
        return operation.action === 'inputStyle'
      }) || {
        span: 24,
        style: {}
      }
    }
  }
}
</script>

<style scoped>
  ul,li {
    padding: 0;
    margin: 0;
    list-style-type: none;
  }
  .li {
    position: relative;
    padding: 0 20px;
  }
  .popover {
    position: absolute;
    right: 0;
    top: 11px;
  }
</style>
